var fs = require('fs');
var exec = require("child_process").exec;

function load(request, response, parameters) {
  var view_id = 'view/convert.html';
  var files_to_convert = file_names_to_convert(parameters);
  
  fs.readFile(view_id, 'utf-8', function(err, data) {
    if(err) {
      var error_message = 'Ocorreu um erro ao tentar carregar o recurso ' + view_id + '.<br>Detalhe: ' + err.toString();
      render_error_page(request, response, error_message);
      console.error('ERROR: ' + error_message);
      
      return;
    }
    
    var converted_files = convert_files(files_to_convert);
    var data_list = [files_to_convert.length];
    
    for (i = 0; i < files_to_convert.length; i++) {
      data_list[i] = new Array(files_to_convert[i], converted_files[i]);
    }
    
    data = data.replace(/<%[\s]*data_table[\s]*%>/, require('../components/data_table').rendered(['Arquivo original', 'Arquivo convertido'], data_list));
    require('../view_handler').render_content(request, response, data);
  });
}

function file_names_to_convert(parameters) {
  files_to_convert = [];
  for (var k in parameters) {
    if (parameters.hasOwnProperty(k)) {
       files_to_convert.push(parameters[k]);
    }
  }
  
  return files_to_convert;
}

function convert_files(files) {
  var converted_files = [];
  
  for (i = 0; i < files.length; i++) {
    try {
      var new_name = files[i] + '.pdf';
      var cmd = 'java -jar lib/jodconverter-cli-2.2.2.jar ~/anexos/' + files[i] + ' ~/anexos/' + new_name;
      exec(cmd);
      console.log(cmd);
      converted_files.push(new_name);
    } catch (err) {
      console.log('ERROR: Não foi possível converter o arquivo ' + files[i] + '\n' + err.stack);
      converted_files.push('Erro de conversão');
    }
  }
  
  return converted_files;
}

exports.load = load;
